import { Component, OnInit ,OnDestroy} from '@angular/core';
import { Router,RouteParams } from '@angular/router-deprecated';
import { Proj } from '../model/proj.model';
import { Group } from '../model/group.model';
import { Api } from '../model/api.model';
import {BaseRequestOptions,Http,Response, HTTP_PROVIDERS,Headers} from '@angular/http';
import { GlobalService } from '../services/global.service';
import { ProjService } from '../services/proj.service';
import { GroupService } from '../services/group.service';
import { ApiService } from '../services/api.service';
@Component({
  selector: 'group-component',
  viewProviders: [HTTP_PROVIDERS,GroupService,ProjService,ApiService],
  templateUrl: 'app/group/tpl/groups.tpl.html'
})
export class GroupsComponent implements OnInit,OnDestroy {

  proj:Proj = new Proj();
  groups:Group[]=[];
  deleteGroupId:string;
  deleteGroupIndex:number;
  allGroups:Group[] =[];
  allDocsByProject:any = {};
  constructor(private router: Router,
    routeParams:RouteParams,
    private apiService:ApiService,
    private groupService: GroupService,
    private projService: ProjService,
    private globalService:GlobalService)
    {
      if(!globalService.getUser())
      {
        this.router.navigate(['Login']);
      }else
      {
        this.proj._id = routeParams.get("projId");
        this.projService.getProj(this.proj._id).subscribe(data=>this.proj = data.json());
        this.groupService.getGroups(this.proj._id).subscribe(data=>this.groups = data.json());

        this.apiService.getApisByProj(this.proj._id).subscribe(data=>{
          this.allDocsByProject = data.json();
        });
      }
  }

  ngOnInit() {
  }

  ngOnDestroy(){

  }

  addGroup()
  {
    this.router.navigate(['AddGroup',{projId:this.proj._id}]);
  }

  addApi(groupId)
  {
    if(groupId)
    {
      this.router.navigate(['AddApiByGroupId',{projId:this.proj._id,groupId:groupId}]);
    }else
    {
      this.router.navigate(['AddApi',{projId:this.proj._id}]);
    }
  }

  gotoApis(groupId,index)
  {
    this.router.navigate(['Apis',{groupId:groupId,projId:this.proj._id}]);
  }

  editGroup(groupId,index)
  {
    this.router.navigate(['EditGroup',{groupId:groupId}]);
  }

  delete(groupId:string,index)
  {
    this.deleteGroupId = groupId;
    this.deleteGroupIndex = index;
    $('.ui.basic.modal')['modal']('show');
  }

  confirmDelete()
  {
    this.groupService.delete(this.deleteGroupId).subscribe(data=>{
      this.groups.splice(this.deleteGroupIndex,1);
      $('.ui.basic.modal')['modal']('hide');
    });
  }

  showApi(apiId)
  {
    this.router.navigate(['ShowApi',{apiId:apiId}]);
  }

  showApis(groupId)
  {
    this.router.navigate(['Apis',{groupId:groupId,projId:this.proj._id}]);
  }

}
